<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/7/20
 * Time: 9:40
 */

namespace app\alliance\controller;


use app\service\MemberCode;
use app\service\MemberService;
use app\service\OcrService;
use app\service\ResourceService;
use app\service\SmsCode;
use app\service\TaskService;
use Protocol\Curl;
use Redis\Redis;
use think\App;
use think\Controller;
use think\Db;

class Login extends Controller
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        header('Access-Control-Allow-Origin:*');  //支持全域名访问，不安全，部署后需要固定限制为客户端网址
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); //支持的http 动作
        header('Access-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers,token');  //响应头 请按照自己需求添加。
        if (strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS') {
            exit;
        }
    }

    function demo()
    {
        $redis = new Redis();
        $redis->hDel('memberInfo', 'AA000001');
        dump(MemberCode::authCode('AA000001', 'ENCODE'));
    }


    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 玩家登陆
     */
    function login()
    {
        # 接收账号(玩家ID / 手机号)
        $account = input('post.account');
        # 接收密码(登录密码 / 手机验证码)
        $pwd = input('post.pwd');
        # 接收mark
        $mark = input('post.mark');
        if (!empty($account) or !empty($pwd)) {
            if (!empty($mark)) {
                $redis = new Redis();
                if (CheckMobile($account)) {
                    $mark = 'phone';
                }
                # 先判断是否注册了
                $register = MemberService::checkMemberRegister($account, $mark);
                if ($register['status']) {
                    # 已经注册(判断验证码/密码)
//                    if ($mark == 'account') {
                    if (!CheckMobile($account)) {
                        # 账号密码登录 , 判断密码是否正确
                        if (md5($pwd) != $register['info']['login_pwd']) {
                            return array('status' => false, 'msg' => '密码错误');
                        }
                    } else {
                        if (md5($pwd) != $register['info']['login_pwd']) {
                            $canLogin = false;
                        } else {
                            $canLogin = true;
                        }
                        if (!$canLogin) {
                            # 手机号验证码登录,判断验证码是否正确(密码也能登录)
                            $redisCode = $redis->hGet('smsCode', strval($account));
                            if (empty($redisCode)) {
                                return array('status' => false, 'msg' => '密码错误');
                            } else {
                                if ($redisCode != $pwd) {
                                    return array('status' => false, 'msg' => '验证码错误');
                                }
                            }
                            # 删除redis
                            $redis->hdel('smsCode', strval($account));
                        }
                    }
                    # 判断玩家状态
                    if ($register['info']['type'] == 3) {
                        return array('status' => false, 'msg' => '账号封停');
                    }
                    if ($register['info']['type'] == 4) {
                        return array('status' => false, 'msg' => '账号已注销');
                    }
                    # 生成token
                    $token = MemberCode::authCode($register['info']['code'], 'ENCODE');

                    $cid = input('post.cid');
                    if (!empty($cid)) {
                        Db::table('member')->where(array('code' => $register['info']['code']))->update(array('cid' => $cid));
                        # 用户信息存入缓存
                        $register['info']['cid'] = $cid;
                    }
                    $redis->hSetJson('memberInfo', $register['info']['code'], $register['info']);
                    # 添加登录记录
                    MemberService::logLogin($register['info']['code'], $register['info']['name']);
                    $register['info']['isActivationSatisfied'] = true;
                    /* $logIntegral = Db::table('log_integral')->where(array('member_code' => $this->code, 'type_branch' => 7))->sum('total_money');
                     if ($logIntegral >= 388) {
                         # 满足激活条件
                         $register['info']['isActivationSatisfied'] = true;
                     } else {
                         # 不满足激活条件
                         $register['info']['isActivationSatisfied'] = false;
                     }*/
                    return array('status' => true, 'msg' => '登录成功', 'info' => $register['info'], 'token' => $token);
                } else {
                    # 未注册
                    return array('status' => false, 'msg' => '未注册 ,请先注册');
                }
            } else {
                # 登录方式为空
                return array('status' => false, 'msg' => '请选择登录方式');
            }
        } else {
            # 存在空值
            if ($mark == 'account') {
                return array('status' => false, 'msg' => '账号/密码为空');
            } elseif ($mark == 'mobile') {
                return array('status' => false, 'msg' => '手机号/验证码为空');
            } else {
                return array('status' => false, 'msg' => '登录方式错误');
            }
        }
    }


    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 发送验证码(登录/注册)
     */
    function getCaptcha()
    {
        # 接收手机号
        $phone = trim(input('post.phone'));
        # 接收操作标识(登录/注册)
        $mark = trim(input('post.mark'));
        if (!empty($phone) or !empty($mark)) {
            # 判断是否已经注册
            $register = MemberService::checkMemberRegister($phone, 'phone');
            if ($mark == 'login') {
                # 登录
                if ($register['status'] == false) {
                    # 未注册
                    return array('status' => false, 'msg' => '未注册,请先注册');
                }
            } elseif ($mark == 'register' or $mark == 'changeMobile') {
                # 注册/修改手机号
                if ($register['status']) {
                    # 手机号已被注册
                    return array('status' => false, 'msg' => '手机号已被注册,请更换手机号');
                }
            } elseif ($mark == 'forget') {
                # 忘记密码
                if ($register['status'] == false) {
                    # 手机号不存在
                    return array('status' => false, 'msg' => '手机号不存在');
                }
            }
            # 生成验证码
            $codeReturn = SmsCode::Ysms($phone);
            if ($codeReturn['status']) {
                return array('status' => true, 'msg' => '发送成功');
            } else {
                return array('status' => false, 'msg' => '发送失败');
            }
        } else {
            # 存在空值
            return array('status' => false, 'msg' => '参数存在空值');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @content 玩家注册
     */
    function register()
    {
        $info = input('post.');
        if (!empty($info['phone'])) {
            $info['p_code'] = strtoupper($info['p_code']);
            $redis = new Redis();
            # 验证是否注册过
            $register = MemberService::checkMemberRegister($info['phone'], 'phone');
            if ($register['status']) {
                # 手机号已被注册
                return array('status' => false, 'msg' => '手机号已被注册,请更换手机号');
            }
            # 验证码比对
            $redisCode = $redis->hGet('smsCode', strval($info['phone']));
            if (empty($redisCode) or $redisCode != $info['code']) {
                return array('status' => false, 'msg' => '验证码错误');
            }
            # 判断填写的两次密码是否一致
            if ($info['pwd'] != $info['pwd_confirm']) {
                return array('status' => false, 'msg' => '两次密码填写不一致');
            }
            # 判断推荐人是否存在
            if (!empty($info['p_code'])) {
                $pInfo = Db::table('member')->field('code')->where("code = '" . strtoupper($info['p_code']) . "' or phone = '" . $info['p_code'] . "'")->find();
                if (empty($pInfo)) {
                    return array('status' => false, 'msg' => '推荐人不存在');
                } else {
                    $info['p_code'] = $pInfo['code'];
                }
            }
            # 删除redis
            $redis->hdel('smsCode', strval($info['phone']));
            # 生成玩家ID
            $memberCodeInfo = MemberCode::getMemberCode($info['p_code']);
            $memberCode = $memberCodeInfo['code'];
            # 状态=>已注册
            $info['status'] = 2;
            # 团队id
            $info['team_id'] = $memberCodeInfo['team_id'];
            # 地址
            $info['address'] = $info['province'] . $info['city'] . $info['area'];
            # 密码加密
            $info['login_pwd'] = md5($info['pwd']);
            # 玩家ID
            $info['code'] = $memberCode;
            # 删除无用字段
            unset($info['pwd_confirm'], $info['pwd']);
            # 注册时间
            $info['register_time'] = TIMESTAMP;
            # 添加玩家信息
            Db::table('member')->table('member')->insert($info);
            # 添加收款信息
            Db::table('member_collection')->insert(array('member_code' => $memberCode));
            # 添加财产信息
            Db::table('member_property')->insert(array('member_code' => $memberCode));
            # 添加生意格子信息
            $gridInfo = array();
            for ($i = 1; $i <= 12; $i++) {
                array_push($gridInfo, array('grid' => $i, 'member_code' => $memberCode));
            }
            Db::table('member_business_grid')->insertAll($gridInfo);
            if (!empty($memberCodeInfo['team_id'])) {
                # 增加团队人数
                Db::table('team')->where(array('id' => $memberCodeInfo['team_id']))->setInc('team_num', 1);
            }
            # 调接口加积分
            $logConsumption = (new Curl())->post(config('leegame.leeBridge_api') . config('leegame.member_consumption'), array('phone' => $info['phone']));
            $logConsumption = json_decode($logConsumption, true);
            addIntegral_branch($logConsumption, $memberCode);
            setActiveMember();
            return array('status' => true, 'code' => $memberCode);
        } else {
            return array('status' => false, 'msg' => '手机号为空');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content 玩家激活
     */
    function activation()
    {
        $info = input('post.');
        $code = strtoupper($info['code']);
        # 操作标识
        $mark = $info['mark'];
        if (!empty($info)) {
            if (!empty($info['idnumber'])) {
                # 判断身份证是否重复
                $memberInfo = Db::table('member')->field('id')
                    ->where(array('idnumber' => $info['idnumber']))->where("code != '" . $code . "'")->find();
                if (!empty($memberInfo)) {
                    return array('status' => false, 'msg' => '身份证号已被注册');
                }
            }
            # 保存图片
            $preg = "/^http(s)?:\\/\\/.+/";
            if (!empty($info['idcard_img'])) {
                # 身份证图片
                if (preg_match($preg, $info['idcard_img'])) {
                    # 没做修改
                    $idcard = $info['idcard_img'];
                } else {
                    # 身份证
                    $idcard = ResourceService::uploadBase($info['idcard_img']);
                    if ($idcard) {
                        $info['idcard'] = $idcard;
                    }
                }
            }
            if (!empty($info['life_img'])) {
                # 生活照
                if (preg_match($preg, $info['life_img'])) {
                    # 没做修改
                    unset($info['life_img']);
                    $lifeImg = $info['life_img'];
                } else {
                    $lifeImg = ResourceService::uploadBase($info['life_img']);
                    if ($lifeImg) {
                        $info['life_img'] = $lifeImg;
                        $info['head_portrait'] = $lifeImg;
                    }
                }
            }
            if ($mark != 'activation') {
                # 身份证验证
                $ocr = new OcrService();
                $ocrRes = $ocr->OcrIdCard($idcard);
                if ($ocrRes['status']) {
                    if ($info['idnumber'] != $ocrRes['IDNumber']) {
                        return array('status' => false, 'msg' => '身份证号填写有误');
                    }
//                    if ($info['name'] != $ocrRes['name']) {
//                        return array('status' => false, 'msg' => '姓名填写有误');
//                    }
                    $info['name'] = $ocrRes['name'];
                    $info['sex'] = getSexInfo($ocrRes['sex']);
//                    if ($info['sex'] != getSexInfo($ocrRes['sex'])) {
//                        return array('status' => false, 'msg' => '性别填写有误');
//                    }
                } else {
                    return $ocrRes;
                }
                # 实名制状态
                $info['realname_status'] = 2;
            }

            # 激活
            if ($mark == 'activation') {
                $res = MemberService::receiveBusiness($code);
                if (!$res['status']) {
                    return $res;
                }
            }
            # 计算年龄
            if (!empty($info['idnumber'])) {
                $info['age'] = getAge($info['idnumber']);
            }
            unset($info['idcard_img'], $info['code'], $info['mark']);
            if ($mark != 'activation') {
                # 实名认证
                $info['real_name'] = $info['name'];
                unset($info['name']);
            } else {
                # 激活
                $info['real_name'] = $info['name'];
            }
            $_res = Db::table('member')->where(array('code' => $code))->update($info);
            if ($_res) {
                # 更新redis
                $redis = new Redis();
                $memberInfo = $redis->hGetJson('memberInfo', $code);
                # 调接口加积分
                $logConsumption = (new Curl())->post(config('leegame.leeBridge_api') . config('leegame.member_consumption'), array('phone' => $memberInfo['phone']));
                $logConsumption = json_decode($logConsumption, true);
                addIntegral_branch($logConsumption, $code);
                if(!empty($idcard)) {
                    $memberInfo['idcard'] = $idcard;
                }
                if(!empty($lifeImg)) {
                    $memberInfo['life_img'] = imgUrl($lifeImg);
                    $memberInfo['head_portrait'] = imgUrl($lifeImg);
                }
                $memberInfo['idnumber'] = $info['idnumber'];
                $memberInfo['sex'] = $info['sex'];
                $memberInfo['age'] = $info['age'];
                if ($mark == 'activation') {
                    $memberInfo['name'] = $info['name'];
                    $memberInfo['real_name'] = $info['name'];
                } else {
                    $memberInfo['realname_status'] = 2;
                    $memberInfo['real_name'] = $info['name'];
                }
                $redis->hSetJson('memberInfo', $code, $memberInfo);
                if ($mark == 'activation') {
                    # 只在激活的时候添加收益
                    if (!empty($memberInfo['p_code'])) {
                        # 添加收益
                        MemberService::recommendedRevenue($memberInfo['p_code'], $code,'activation');
                    }
                }
                $memberInfo = $redis->hGetJson('memberInfo', $code);
                return array('status' => true, 'msg' => '成功', 'integral' => $memberInfo['integral']);
            } else {
                return array('status' => false, 'msg' => '认证失败');
            }
        } else {
            return array('status' => false, 'msg' => '请补全信息');
        }
    }

    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @content  忘记密码
     */
    function forgetPwd()
    {
        $info = input('post.');
        # 验证是否注册过
        $register = MemberService::checkMemberRegister($info['phone'], 'phone');
        if ($register['status'] == false) {
            # 手机号不存在
            return array('status' => false, 'msg' => '手机号不存在');
        }
        $redis = new Redis();
        # 验证码比对
        $redisCode = $redis->hGet('smsCode', strval($info['phone']));
        if (empty($redisCode) or $redisCode != $info['code']) {
            return array('status' => false, 'msg' => '验证码错误');
        }
        # 判断填写的两次密码是否一致
        if ($info['pwd'] != $info['pwd_confirm']) {
            return array('status' => false, 'msg' => '两次密码填写不一致');
        }
        $memberInfo = $redis->hGetJson('memberInfo', $register['info']['code']);
        if ($info['mark'] == 'login') {
            # 登录密码
            $res = Db::table('member')->where(array('phone' => $info['phone']))->update(array('login_pwd' => md5($info['pwd'])));
            $memberInfo['login_pwd'] = md5($info['pwd']);
        } elseif ($info['mark'] == 'operation') {
            # 操作密码
            $res = Db::table('member')->where(array('phone' => $info['phone']))->update(array('operate_pwd' => md5($info['pwd'])));
            $memberInfo['operate_pwd'] = md5($info['pwd']);
        }
        $redis->hSetJson('memberInfo', $register['info']['code'], $memberInfo);
        if ($res) {
            return array('status' => true, 'msg' => '修改成功');
        } else {
            return array('status' => false, 'msg' => '修改失败');
        }
    }

    /**
     * @return array
     * @context 更新版本
     */
    public function up_version()
    {
        $appid = input("post.appid");
        $version = input("post.version"); //客户端版本号
        $rsp = array("status" => true, "up_status" => false); //默认返回值，不需要升级
        if (isset($appid) && isset($version)) {
            $info = $this->getsVersionControl();
            if (!empty($info) and $appid === $info['appid']) { //校验appid
                if (!in_array($version, $info['version_list'])) { //这里是示例代码，真实业务上，最新版本号及relase notes可以存储在数据库或文件中
                    $rsp["up_status"] = true;
                }
            }
            $rsp['version'] = $info['version'];
            $rsp["note"] = $info['note']; //release notes
            $rsp["url"] = $info['url']; //应用升级包下载地址
            $rsp['force_update'] = $info['force_update'];
        }
        return $rsp;
    }

    function getsVersionControl()
    {
        $_redis = new Redis();
        $list = $_redis->hGetJson("version", "control");
        if (empty($list)) {
            $list = Db::table("version_control")->order("id desc")->find();

            # 查询强制更新之后的版本
            $version_list = Db::table("version_control")->field("version")
                ->where(" id >= ifnull((select id from version_control where force_update=1 order by id desc limit 1,0),0)")->select();

            $list['version_list'] = array_values(array_column($version_list, 'version'));
            $_redis->hSetJson("version", "control", $list);
        }
        return $list;
    }

    /**
     * @return array
     * @context 返回云盟商桥地址
     */
    function bridgeUrl()
    {
        return array("status" => true, "url" => "http://yun.youpilive.com/api/index/DownLoadApk");
    }
}